package lium.lbs.lbsim.fragments;

import android.os.Bundle;
import android.support.annotation.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.lmlibrary.R;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import com.lzy.okgo.OkGo;
import lium.lbs.lbsim.OBaseFragment;


public abstract class BaseFragment extends OBaseFragment implements View.OnClickListener {
    private View contentView;
    private FrameLayout userContent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (contentView != null) {
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
            return contentView;
        }
        contentView = inflater.inflate(R.layout.lb_activity_base_content, container, false);
        userContent = contentView.findViewById(R.id.content);
        if (getLayoutId() == 0)
            return contentView;
        View view = inflater.inflate(getLayoutId(), null);
        userContent.addView(view);
        if (contentView == null) {
            return null;
        }
        //initArguments(getArguments());
        return contentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    /**
     * 初始化控件
     */
    protected abstract void initView();

    protected abstract @LayoutRes
    int getLayoutId();


    public void addOnClickListeners(@IdRes int... ids) {
        if (ids != null) {
            for (@IdRes int id : ids) {
                userContent.findViewById(id).setOnClickListener(this);
            }
        }
    }


    public CompositeDisposable mCompositeDisposable;

    /**
     * 添加订阅
     */
    public void addDisposable(Disposable mDisposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(mDisposable);
    }


    /**
     * 取消所有订阅
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        clearDisposable();
    }

}